package com.example.demo.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.demo.common.AuthAccess;
import com.example.demo.common.Constants;
import com.example.demo.entity.User;
import com.example.demo.exception.ServiceException;
import com.example.demo.mapper.UserMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


/**
 * JWT 拦截器
 *
 * @author He Dong
 * @date 2023/12/19
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
        }
        // 如果不是映射到方法直接通过
        if (handler instanceof HandlerMethod) {
            AuthAccess annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthAccess.class);
            if (annotation != null) {
                return true;
            }
        }
        // 执行认证
        if (StringUtils.isBlank(token)) {
            throw new ServiceException(Constants.AUTH_CODE, "请先登录");
        }
        // 获取 token 中的 account
        String account;
        try {
            account = JWT.decode(token).getAudience().get(0);
            System.out.println("account："+account);
            String  redisToken= redisTemplate.opsForValue().get("token:" + account);
            if (!token.equals(redisToken)){
                throw new ServiceException(Constants.AUTH_CODE, "请先登录");
            }
        } catch (JWTDecodeException j) {
            throw new ServiceException(Constants.AUTH_CODE, "请先登录");
        }
        // 根据token中的userid查询数据库
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("account",account);
        User user = userMapper.selectOne(wrapper);
        if (user == null) {
            throw new ServiceException(Constants.AUTH_CODE, "请先登录");
        }
        // 用户密码加签生成验证器
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token); // 验证token
        } catch (JWTVerificationException e) {
            throw new ServiceException(Constants.AUTH_CODE, "请先登录");
        }
        return true;
    }
}